﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace MySpiderMgr.Infrastructure.CommonHelpers
{
    public class EncryptAndDecrypt
    {

        /// <summary>
        /// 获取MD5
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Get32MD5(string source)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            //获取密文字节数组
            byte[] bytResult = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(source));
            //转换成字符串，32位
            string strResult = BitConverter.ToString(bytResult).Replace("-", "");

            return strResult.ToUpper();
        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DESEncrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = Encoding.UTF8.GetBytes(Text);

            string md5SKey = Get32MD5(sKey).Substring(0, 8);

            des.Key = Encoding.UTF8.GetBytes(md5SKey);

            des.IV = Encoding.UTF8.GetBytes(md5SKey);

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);

            cs.FlushFinalBlock();

            StringBuilder sValue = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                sValue.AppendFormat("{0:X2}", b);
            }
            return sValue.ToString();
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DESDecrypt(string Text, string sKey = null)
        {

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            string md5SKey = Get32MD5(sKey).Substring(0, 8);
            des.Key = Encoding.UTF8.GetBytes(md5SKey);
            des.IV = Encoding.UTF8.GetBytes(md5SKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}
